﻿namespace ConfigDatabase.Class
{
    using System;
    using System.Data;
    using System.IO;
    using System.Security.Cryptography;
    using System.Text;

    public class ConnectDatabase
    {
        private string _address = "";
        private const string _conDatabsae = "5";
        private const string _conPass = "4";
        private const string _conPort = "2";
        private const string _conSchema = "6";
        private const string _conServer = "1";
        private const string _conUser = "3";
        private string _database = "";
        private string _pass = "";
        private string _pathconnect;
        private int _port = -1;
        private string _schema = "";
        private string _stringconnect = "";
        private string _user = "";
        private DataSet dsthongso = new DataSet();

        public ConnectDatabase()
        {
            this.PathConnect = @"xml\connect.xml";
        }

        private void ConnectToFile(string pathxml)
        {
            try
            {
                this.dsthongso.ReadXml(pathxml, XmlReadMode.ReadSchema);
                this._address = this.DecryptString(this.dsthongso.Tables[0].Rows[0]["1"].ToString(), "abc");
                this._port = int.Parse(this.DecryptString(this.dsthongso.Tables[0].Rows[0]["2"].ToString(), "abc"));
                this._user = this.DecryptString(this.dsthongso.Tables[0].Rows[0]["3"].ToString(), "abc");
                this._pass = this.DecryptString(this.dsthongso.Tables[0].Rows[0]["4"].ToString(), "abc");
                this._database = this.DecryptString(this.dsthongso.Tables[0].Rows[0]["5"].ToString(), "abc");
                this._schema = this.DecryptString(this.dsthongso.Tables[0].Rows[0]["6"].ToString(), "abc");
            }
            catch
            {
                if ((this.dsthongso.Tables.Count == 0) || (this.dsthongso.Tables[0].Rows.Count == 0))
                {
                    this.TaoDataTable();
                }
                this.dsthongso.Tables[0].Rows[0]["1"] = this._address = "localhost";
                this._port = 0x1538;
                this.dsthongso.Tables[0].Rows[0]["2"] = this._port.ToString();
                this.dsthongso.Tables[0].Rows[0]["3"] = this._user = "enterprisedb";
                this.dsthongso.Tables[0].Rows[0]["4"] = this._pass = "enterprisedb";
                this.dsthongso.Tables[0].Rows[0]["5"] = this._database = "postgres";
                this.dsthongso.Tables[0].Rows[0]["6"] = this._schema = "sys";
                this.SaveFileConnect();
            }
        }

        public string DecryptString(string Message, string Passphrase)
        {
            byte[] buffer;
            UTF8Encoding encoding = new UTF8Encoding();
            MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();
            byte[] buffer2 = provider.ComputeHash(encoding.GetBytes(Passphrase));
            TripleDESCryptoServiceProvider provider2 = new TripleDESCryptoServiceProvider {
                Key = buffer2,
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            byte[] inputBuffer = Convert.FromBase64String(Message);
            try
            {
                buffer = provider2.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
            }
            finally
            {
                provider2.Clear();
                provider.Clear();
            }
            return encoding.GetString(buffer);
        }

        public string EncryptString(string Message, string Passphrase)
        {
            byte[] buffer;
            UTF8Encoding encoding = new UTF8Encoding();
            MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider();
            byte[] buffer2 = provider.ComputeHash(encoding.GetBytes(Passphrase));
            TripleDESCryptoServiceProvider provider2 = new TripleDESCryptoServiceProvider {
                Key = buffer2,
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            byte[] bytes = encoding.GetBytes(Message);
            try
            {
                buffer = provider2.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length);
            }
            finally
            {
                provider2.Clear();
                provider.Clear();
            }
            return Convert.ToBase64String(buffer);
        }

        ~ConnectDatabase()
        {
            this._address = null;
            this._database = null;
            this._pass = null;
            this._schema = null;
            this._stringconnect = null;
            this._user = null;
            this._pathconnect = null;
            this.dsthongso = null;
            GC.WaitForPendingFinalizers();
        }

        public void SaveFileConnect()
        {
            string[] strArray = this._pathconnect.Split(new char[] { '\\' });
            string path = this._pathconnect.Replace(strArray[strArray.Length - 1], "");
            if ((this.dsthongso.Tables.Count == 0) || (this.dsthongso.Tables[0].Rows.Count == 0))
            {
                this.TaoDataTable();
            }
            this.dsthongso.Tables[0].Rows[0]["1"] = this.EncryptString(this._address, "abc");
            this.dsthongso.Tables[0].Rows[0]["2"] = this.EncryptString(this._port.ToString(), "abc");
            this.dsthongso.Tables[0].Rows[0]["3"] = this.EncryptString(this._user, "abc");
            this.dsthongso.Tables[0].Rows[0]["4"] = this.EncryptString(this._pass, "abc");
            this.dsthongso.Tables[0].Rows[0]["5"] = this.EncryptString(this._database, "abc");
            this.dsthongso.Tables[0].Rows[0]["6"] = this.EncryptString(this._schema, "abc");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            this.dsthongso.WriteXml(path + strArray[strArray.Length - 1], XmlWriteMode.WriteSchema);
        }

        public void SaveFileConnect(string path, string filename)
        {
            if ((this.dsthongso.Tables.Count == 0) || (this.dsthongso.Tables[0].Rows.Count == 0))
            {
                this.TaoDataTable();
            }
            this.dsthongso.Tables[0].Rows[0]["1"] = this.EncryptString(this._address, "abc");
            this.dsthongso.Tables[0].Rows[0]["2"] = this.EncryptString(this._port.ToString(), "abc");
            this.dsthongso.Tables[0].Rows[0]["3"] = this.EncryptString(this._user, "abc");
            this.dsthongso.Tables[0].Rows[0]["4"] = this.EncryptString(this._pass, "abc");
            this.dsthongso.Tables[0].Rows[0]["5"] = this.EncryptString(this._database, "abc");
            this.dsthongso.Tables[0].Rows[0]["6"] = this.EncryptString(this._schema, "abc");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            this.dsthongso.WriteXml(path + filename, XmlWriteMode.WriteSchema);
            this._pathconnect = path + filename;
        }

        private void TaoDataTable()
        {
            this.dsthongso = new DataSet();
            this.dsthongso.Tables.Add("thongso");
            this.dsthongso.Tables[0].Columns.Add("1");
            this.dsthongso.Tables[0].Columns.Add("2");
            this.dsthongso.Tables[0].Columns.Add("3");
            this.dsthongso.Tables[0].Columns.Add("4");
            this.dsthongso.Tables[0].Columns.Add("5");
            this.dsthongso.Tables[0].Columns.Add("6");
            DataRow row = this.dsthongso.Tables[0].NewRow();
            this.dsthongso.Tables[0].Rows.Add(row);
        }

        public static void TrackingError(string error, string Funtion, string filename)
        {
            DataSet set = new DataSet();
            try
            {
                if (!Directory.Exists("error"))
                {
                    Directory.CreateDirectory("error");
                }
                set.ReadXml(@"error\" + DateTime.Now.ToString("ddMMyyyy") + ".xml");
            }
            catch
            {
                set = new DataSet();
                set.Tables.Add("error");
                set.Tables[0].Columns.Add("Time");
                set.Tables[0].Columns.Add("Message");
                set.Tables[0].Columns.Add("Funtion");
                set.Tables[0].Columns.Add("FileName");
            }
            DataRow row = set.Tables[0].NewRow();
            row[0] = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
            row[1] = error;
            row[2] = Funtion;
            row[3] = filename;
            set.Tables[0].Rows.InsertAt(row, 0);
            set.WriteXml(@"error\" + DateTime.Now.ToString("ddMMyyyy") + ".xml");
        }

        public string Database
        {
            get
            {
                return this._database;
            }
            set
            {
                this._database = value;
            }
        }

        public string IpAdress
        {
            get
            {
                return this._address;
            }
            set
            {
                this._address = value;
            }
        }

        public bool KiemTraFileConnect
        {
            get
            {
                return (this._database == "postgres");
            }
        }

        public string PassWord
        {
            get
            {
                return this._pass;
            }
            set
            {
                this._pass = value;
            }
        }

        public string PathConnect
        {
            get
            {
                return this._pathconnect;
            }
            set
            {
                this._pathconnect = value;
                this.ConnectToFile(this._pathconnect);
            }
        }

        public int Port
        {
            get
            {
                return this._port;
            }
            set
            {
                this._port = value;
            }
        }

        public string Schema
        {
            get
            {
                return this._schema;
            }
            set
            {
                this._schema = value;
            }
        }

        public string StringConnect
        {
            get
            {
                this._stringconnect = string.Concat(new object[] { "Server=", this._address, ";Port=", this._port, ";User Id=", this._user, ";Password=", this._pass, ";Database=", this._database, ";Encoding=UNICODE;Pooling=true;" });
                return this._stringconnect;
            }
        }

        public string User
        {
            get
            {
                return this._user;
            }
            set
            {
                this._user = value;
            }
        }
    }
}

